<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\AliOosService;
use app\admin\service\CommunityService;
use app\admin\service\DemandService;
use app\admin\service\RecruitRejectService;
use app\admin\service\EnterpriseRejectService;
use app\admin\service\EnterpriseService;
use app\admin\service\RecruitService;
use app\admin\service\LocationService;
use app\admin\service\ResourceCateService;
use app\admin\service\ResourceCheckPathService;
use app\admin\service\ResourceCheckService;
use app\admin\service\ResourceInitNumsService;
use app\admin\service\ResourcePathService;
use app\admin\service\ResourceSaleFeedbackService;
use app\admin\service\ResourceService;
use app\admin\service\ResourceViewLogService;
use app\admin\service\ResourceViewService;
use app\admin\validate\Resource as resourceValidate;
use app\AdminController;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 审核管理
 * Class Check
 * @package app\admin\controller
 */
class Check extends AdminController
{
    /**
     * 列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $type = intval($this->request->param('type', 1));
        switch ($type) {
            case 2:
                $placeholder = '名称|编号|城市|标签';
                $whereLike = 'd.name|d.s_number|d.label|c.name';
                break;
            case 3:
                $placeholder = '企业|行业|地区';
                $whereLike = 'e.name|ce.name|c.name';
                break;
            case 4:
                $placeholder = '职位|企业|发布者';
                $whereLike = 'er.position|e.name|u.nickname';
                break;
            case 5:
                $placeholder = '社群|行业|企业|创建者';
                $whereLike = 'r.name|c.name|e.name|u.nickname';
                break;
            default:
                $placeholder = '名称|企业|城市|行业';
                $whereLike = 'r.name|r.company|l.name|c.name';
        }

        if (request()->isPost()) {
            $where = [];
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($keywords) {
                $where[] = [$whereLike, 'like', '%' . $keywords . '%'];
            }

            // 社群列表
            if ($type == 1) {
                $list = ResourceService::getCheckList($where, $this->page, $this->pagesize);
                $count = ResourceService::countCheckList($where);
                // 需求列表
            } else if ($type == 2) {
                $where[] = ['d.status', '=', 2];
                $list = DemandService::getDemandList($where, $this->page, $this->pagesize, 2);
                $count = DemandService::countDemandList($where);
                // 企业认证
            } else if ($type == 3) {
                $where[] = ['e.status', 'in', [0, -1]];
                $list = EnterpriseService::getEnterpriseList($where, $this->page, $this->pagesize);
                $count = EnterpriseService::countEnterpriseList($where);
                // 企业招聘
            } else if ($type == 4) {
                $where[] = ['er.status', 'in', [0, -1]];
                $list = RecruitService::getRecruitList($where, $this->page, $this->pagesize);
                $count = RecruitService::countRecruitList($where);
                // 企业社群
            } else {
                $where[] = ['r.status', 'in', [0, -1]];
                $list = CommunityService::getCommunityList($where, $this->page, $this->pagesize);
                $count = CommunityService::countCommunityList($where);
            }

            return adminResponseJson(['type' => $type, 'placeholder' => $placeholder, 'list' => $list, 'count' => $count]);
        }

        // 总社群
        $countResource = ResourceService::countResource();
        // 审核中
        $resourceCheck = ResourceCheckService::countResourceCheck(['status' => 0]);
        // 已通过
        $resourcePass = ResourceCheckService::countResourceCheck(['status' => 1]);
        // 被驳回
        $resourceReject = ResourceCheckService::countResourceCheck(['status' => 2]);
        // 总需求
        $countDemand = DemandService::countDemand();
        // 审核中
        $demandCheck = DemandService::countDemandList(['d.status' => 2]);
        // 已完成
        $demandCompleted = DemandService::countDemandList(['d.status' => 3]);
        return view('', [
            'type' => $type,
            'placeholder' => $placeholder,
            'check_data' => [
                'resourceCheck' => $resourceCheck,
                'resourceLastCheck' => $countResource - $resourceCheck,
                'resourceCheckScale' => round(($resourceCheck / $countResource) * 100, 2) . '%',
                'resourcePass' => $resourcePass,
                'resourceLastPass' => $countResource - $resourcePass,
                'resourcePassScale' => round(($resourcePass / $countResource) * 100, 2) . '%',
                'resourceReject' => $resourceReject,
                'resourceLastReject' => $countResource - $resourceReject,
                'resourceRejectScale' => round(($resourceReject / $countResource) * 100, 2) . '%'
            ],
            'demand_data' => [
                'countDemand' => $countDemand,
                'demandCheck' => $demandCheck,
                'demandLastCheck' => $countDemand - $demandCheck,
                'demandCheckScale' => round(($demandCheck / $countDemand) * 100, 2) . '%',
                'demandCompleted' => $demandCompleted,
                'demandLastCompleted' => $countDemand - $demandCompleted,
                'demandCompletedScale' => round(($demandCompleted / $countDemand) * 100, 2) . '%',
            ],
        ]);
    }

    /**
     * 社群审核编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resourceCheckEdit()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = ResourceCheckService::findResourceCheck(['id' => $id]);
        $info['yqrcode'] = $info['qrcode'] ? config('url.url') . $info['qrcode'] : '';
        $info['ylogo'] = $info['logo'] ? config('url.url') . $info['logo'] : '';

        // 格式化图片和视频
        $path_list = ResourceCheckPathService::getResourceCheckPath(['rid' => $info['id']]);
        $info['images_list'] = '';
        $info['images_path'] = '';
        $yImagesArr = [];
        if ($path_list) {
            $path = '';
            $images_path = '';
            foreach ($path_list as $v) {
                $path .= config('url.url') . $v['path'] . ',';
                $images_path .= $v['path'] . ',';
                $yImagesArr[] = $v['path'];
            }
            $info['images_list'] = rtrim($path, ',');
            $info['images_path'] = rtrim($images_path, ',');
        }

        if (request()->isPost()) {
            $data = $this->request->post();

            try {
                validate(resourceValidate::class)->resourceEdit()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if (intval($data['uid']) < 1) {
                $this->error(adminJsonMsg(1006));
            }

            // 获取社群编号
            if ($data['uid'] != $info['uid']) {
                $data['number'] = getResourceNumber($data['uid']);
            }
            $res = ResourceCheckService::updateResourceCheck($data, ['id' => $data['id']]);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            $pathArr = [];
            $addArr = [];

            // 更改了logo
            if ($data['logo'] != $info['logo']) {
                if ($info['logo']) {
                    $pathArr[] = $info['logo'];
                }
                if ($data['logo']) {
                    $addArr[] = $data['logo'];
                }
            }

            // 更改了二维码
            if ($data['qrcode'] != $info['qrcode']) {
                $pathArr[] = $info['qrcode'];
                $addArr[] = $data['qrcode'];
            }

            $imageArr = $data['images'] ? explode(',', $data['images']) : [];

            // 比对是否新增了封面图片
            $savePathArr = array_diff($imageArr, $yImagesArr);

            if ($savePathArr) {
                // 存储图片/视频路径到指定表
                foreach ($savePathArr as $type => $path) {
                    ResourceCheckPathService::createResourceCheckPath([
                        'path' => $path,
                        'type' => 1,
                        'rid' => $data['id'],
                    ]);
                }

                AliOosService::uploadAliOos($savePathArr);
            }

            AliOosService::uploadAliOos($addArr);


            // 比对是否删除了封面图片
            $delPathArr = array_diff($yImagesArr, $imageArr);

            // 删除图片/视频所在表位置
            if ($delPathArr) {
                foreach ($delPathArr as $paths) {
                    ResourceCheckPathService::delResourceCheckPath(['rid' => $data['id'], 'path' => $paths]);
                }
            }

            // 跳转回去审核列表
            $this->success(adminJsonMsg(1004), (STRING)url('/check/index') . '?type=1');
        }

        // 二级分类
        $resourceCate = ResourceCateService::getResourceCate();
        // 省份
        $province = LocationService::getProvince();
        // 城市
        $city = LocationService::getCity($info['province']);
        // 地区
        $area = LocationService::getArea($info['city']);
        return view('', [
            'info' => $info,
            'resourceCate' => $resourceCate,
            'province' => $province,
            'city' => $city,
            'area' => $area,
        ]);
    }

    /**
     * 社群驳回
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resourceReject()
    {
        if (request()->isPost()) {
            $param = $this->request->param();

            $where = ['id' => intval($param['id'])];

            $info = ResourceCheckService::findResourceCheck($where);

            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            $res = ResourceCheckService::updateResourceCheck(['status' => -1, 'reject_time' => time(), 'reject_reason' => $param['reject_reason']], $where);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            $this->success(adminJsonMsg(1004));
        }
    }

    /**
     * 社群通过
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resourcePass()
    {
        if (request()->isPost()) {
            $id = intval($this->request->param('id'));

            $where = ['id' => $id];

            $info = ResourceCheckService::findResourceCheck($where);

            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            // 启动事务
            Db::startTrans();
            try {

                ResourceCheckService::updateResourceCheck(['status' => 1, 'check_time' => time()], $where);

                $imageArr = ResourceCheckPathService::getResourceCheckPath(['rid' => $info['id']]);
                unset($info['id'], $info['reject_reason'], $info['check_time']);

                $info['create_time'] = strtotime($info['create_time']);
                $info['update_time'] = strtotime($info['update_time']);
                $info['status'] = 1;
                $info['number'] = getResourceNumber($info['uid']);
                $res = ResourceService::createResource($info);

                // 存储图片/视频路径到指定表
                foreach ($imageArr as $val) {
                    ResourcePathService::createResourcePath([
                        'path' => $val['path'],
                        'type' => $val['type'],
                        'create_time' => strtotime($val['create_time']),
                        'rid' => $res->id,
                    ]);
                }

                // 给当前用户增加社群可查看次数
                $initNums = ResourceInitNumsService::findResourceInitNums();
                $result = ResourceViewLogService::createResourceViewLog([
                    'rid' => $res->id,
                    'uid' => $info['uid'],
                    'desc' => '添加社群',
                    // 1查看社群  2添加社群
                    'type' => 2,
                    'nums' => '+' . $initNums['acc_nums'],
                ]);
                if ($result) {
                    $finds = ResourceViewService::findResourceView(['uid' => $info['uid']]);
                    if (!$finds) {
                        ResourceViewService::createResourceView(['uid' => $info['uid'], 'nums' => $initNums['init_nums'] + $initNums['acc_nums']]);
                    } else {
                        ResourceViewService::updateResourceView([
                            'nums' => $finds['nums'] + $initNums['acc_nums']
                        ], ['uid' => $info['uid']]);
                    }
                }

                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success(adminJsonMsg(1004));
        }
    }

    /**
     * 需求反馈回复
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function demandFeedBackReply()
    {
        if (request()->isPost()) {
            $id = intval($this->request->param('id', 0));
            $info = ResourceSaleFeedbackService::findResourceSaleFeedback(['f.id' => $id]);
            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            if ($info['status']) {
                $this->error(adminJsonMsg(10013));
            }

            $reply = trim($this->request->param('reply', ''));

            $res = ResourceSaleFeedbackService::updateResourceSaleFeedback([
                'reply' => $reply, 'reply_time' => time(), 'status' => 1], ['id' => $id]);

            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            $this->success(adminJsonMsg(1004));
        }
    }
}